package com.purvar.sevice;

import com.purvar.dto.HolidayVo;
import com.purvar.dto.TaskVo;
import groovy.util.logging.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricDetail;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.impl.persistence.entity.HistoricDetailVariableInstanceUpdateEntityImpl;
import org.flowable.engine.impl.persistence.entity.HistoricProcessInstanceEntityImpl;
import org.flowable.engine.repository.Deployment;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class LeaveFlowService {
    private  final Logger logger = LoggerFactory.getLogger(LeaveFlowService.class);
    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private HistoryService historyService;


    public void deployProcess() {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("processes/leaveFlow.bpmn20.xml").deploy();
        logger.info("leaveFlow部署---结束");
    }

    public void startProcess(String key) {
        runtimeService.startProcessInstanceByKey(key);
        logger.info("leaveFlow启动任务--结束");
    }

    @Transactional
    public String applyProcess(String key, String name,String days) {
        String res = "leaveFlow发起申请--成功";
        Map<String, Object> variables = new HashMap();
        variables.put("name", name);
        variables.put("days", days);
        List<Task> list= taskService.createTaskQuery().taskDefinitionKey(key).list();
        if(list.size()>0){
            taskService.complete(taskService.createTaskQuery().taskDefinitionKey(key).list().get(0).getId(),variables);
        }else{
            res = "没有可以发起的申请，需要先启动任务。";
            logger.info(res);
        }
        logger.info("leaveFlow发起申请--结束");
        return res;
    }

    @Transactional
    public String approveProcess(String key, String name, String approveFlag) {
        String res = "leaveFlow发起审批--成功";
        Map<String, Object> variables = new HashMap();
        variables.put("approveName", name);
        variables.put("approveFlag", approveFlag);
        List<Task> list= taskService.createTaskQuery().taskDefinitionKey(key).list();
        if(list.size()>0){
            taskService.complete(taskService.createTaskQuery().taskDefinitionKey(key).list().get(0).getId(),variables);
        }else{
            res = "没有可以发起的审批，需要先做申请任务。";
            logger.info(res);
        }
        logger.info("leaveFlow发起审批--结束");
        return res;
    }

    @Transactional
    public List<TaskVo> getTasks() {
        List<Task> tasks = new ArrayList<>();
        tasks.addAll(taskService.createTaskQuery().list());
        List<TaskVo> dtos = new ArrayList<>();
        for (Task task : tasks) {
            TaskVo taskVo=new TaskVo(task.getId(), task.getName(),task.getCreateTime(),null);
            HolidayVo holidayVo=new HolidayVo();
            holidayVo.setName((String)taskService.getVariable(task.getId(),"name"));
            holidayVo.setDays((String)taskService.getVariable(task.getId(),"days"));
            holidayVo.setApproveFlag((String)taskService.getVariable(task.getId(),"approveFlag"));
            taskVo.setHolidayVo(holidayVo);
            dtos.add(taskVo);
        }
        return dtos;
    }

    @Transactional
    public List<TaskVo> historyTasks() {
        List<TaskVo> dtos = new ArrayList<>();
        List<HistoricProcessInstance> listPage =
                historyService.createHistoricProcessInstanceQuery().processDefinitionKey("leaveFlow")
                        .orderByProcessInstanceEndTime().desc().listPage(0,15);
        for(HistoricProcessInstance hs : listPage){
            HistoricProcessInstanceEntityImpl hhs = (HistoricProcessInstanceEntityImpl)hs;
            String processInstanceId =hhs.getProcessInstanceId();
            List<HistoricDetail> list= historyService.createHistoricDetailQuery().processInstanceId(processInstanceId).list();
            Map map = new HashMap();
            for(HistoricDetail item :list){
                HistoricDetailVariableInstanceUpdateEntityImpl hItem = (HistoricDetailVariableInstanceUpdateEntityImpl) item;
                map.put(hItem.getName(),hItem.getTextValue());
            }
            TaskVo taskVo=new TaskVo(processInstanceId,"",hhs.getStartTime(),hhs.getEndTime());
            HolidayVo holidayVo=new HolidayVo();
            holidayVo.setName((String)map.get("name"));
            holidayVo.setDays((String)map.get("days"));
            holidayVo.setApproveName((String)map.get("approveName"));
            holidayVo.setApproveFlag((String)map.get("approveFlag"));
            taskVo.setHolidayVo(holidayVo);
            dtos.add(taskVo);
        }
        return dtos;
    }
}
